﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using QLK.Database;
using QLK.Database.BLLs;
using QLK.Web.App_Code;

namespace QLK.Web
{
    public partial class ProductsDetails : System.Web.UI.Page
    {
        ProductBLL productsBLL = new ProductBLL();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                Load_Data();
        }

        private void Load_Data()
        {
            grvProducts.DataSource = productsBLL.ProductGetAll();
            grvProducts.DataBind();
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect(PageUrls.Products);
        }

        protected void grvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvProducts.PageIndex = e.NewPageIndex;
            Load_Data();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            CheckBox ck;

            for (int i = 0; i < grvProducts.Rows.Count; i++)
            {
                ck = (CheckBox)grvProducts.Rows[i].Cells[1].FindControl("ckDelete");

                if (ck.Checked == true)
                {
                    int productid = int.Parse(grvProducts.Rows[i].Cells[2].Text.ToString());

                    if (productsBLL.ProductDeleteByID(productid))
                    {
                        Load_Data();
                        lblWarning.Text = "Success";
                    }
                    else
                        lblWarning.Text = "fails";
                }
            }
        }

        protected void ImgEdit_Click(object sender, ImageClickEventArgs e)
        {
            GridViewRow gvRow = (GridViewRow)(sender as Control).Parent.Parent;
            int index = gvRow.RowIndex;
            Image img = (Image)grvProducts.Rows[index].Cells[7].FindControl("ImgProduct");

            Product pro = new Product();
            pro.ProductID = int.Parse(grvProducts.Rows[index].Cells[2].Text.ToString());
            pro.UPC = grvProducts.Rows[index].Cells[3].Text.ToString();
            pro.ProductName = grvProducts.Rows[index].Cells[4].Text.ToString();
            pro.CategoryID = int.Parse(grvProducts.Rows[index].Cells[5].Text.ToString());
            pro.Manufacture = grvProducts.Rows[index].Cells[6].Text.ToString();
            pro.Image = img.ImageUrl.ToString();

            Response.Redirect(string.Format("{0}?{1}={2}&{3}={4}&{5}={6}&{7}={8}&{9}={10}&{11}={12}",
               PageUrls.Products, Columns.ProductID, pro.ProductID, Columns.UPC, pro.UPC,
               Columns.ProductName, pro.ProductName, Columns.CategoryID, pro.CategoryID,
               Columns.Manufacture, pro.Manufacture, Columns.Image, pro.Image));
        }
    }
}
